package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.AitesAdapter;
import com.github.postsanf.yinian.bean.YNAite;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNAiteResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class AiteSelectActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView members_recycler;
    private AitesAdapter mAdapter;
    private List<YNAite> ynAiteList = new ArrayList<>();
    private HorizontalScrollView aite_hsv;
    private TextView aite_hsv_tip;
    private EditText edit_text;
    private TextView edit_text_sure;
    private LinearLayout aite_sel_hor;
    private List<TextView> textViews = new ArrayList<>();
    public static List<String> phoneNames = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_aite_select);
        initView();
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("updatephonetag");
        myIntentFilter.addAction("deletephonetag");
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        sendBroadcast(new Intent("updateeditphone"));
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "updatephonetag":
                    String phonename = intent.getStringExtra("phonename");
                    aite_sel_hor.addView(CreateTextView(phonename, true));
                    if (phoneNames.size() > 0) {
                        aite_hsv_tip.setVisibility(View.GONE);
                        aite_hsv.setVisibility(View.VISIBLE);
                    } else {
                        aite_hsv.setVisibility(View.GONE);
                        aite_hsv_tip.setVisibility(View.VISIBLE);
                    }
                    break;
                case "deletephonetag":
                    String delphonename = intent.getStringExtra("delphonename");
                    for (int i = 0; i < phoneNames.size(); i++) {
                        if (delphonename.equals(phoneNames.get(i))) {
                            phoneNames.remove(i);
                        }
                    }
                    for (int i = 0; i < textViews.size(); i++) {
                        if (delphonename.equals(textViews.get(i).getText().toString())) {
                            textViews.remove(i);
                            aite_sel_hor.removeViewAt(i);
                        }
                    }
                    if (phoneNames.size() > 0) {
                        aite_hsv_tip.setVisibility(View.GONE);
                        aite_hsv.setVisibility(View.VISIBLE);
                    } else {
                        aite_hsv.setVisibility(View.GONE);
                        aite_hsv_tip.setVisibility(View.VISIBLE);
                    }
                    break;

            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.tv_phone).setOnClickListener(this);
        aite_hsv = (HorizontalScrollView) findViewById(R.id.aite_hsv);
        aite_hsv_tip = (TextView) findViewById(R.id.aite_hsv_tip);
        edit_text = (EditText) findViewById(R.id.edit_text);
        edit_text_sure = (TextView) findViewById(R.id.edit_text_sure);
        edit_text_sure.setOnClickListener(this);
        aite_sel_hor = (LinearLayout) findViewById(R.id.aite_sel_hor);
        aite_sel_hor.removeAllViews();
        textViews.clear();
        members_recycler = (RecyclerView) findViewById(R.id.members_recycler);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        members_recycler.setLayoutManager(linearLayoutManager);
        members_recycler.setHasFixedSize(true);
        mAdapter = new AitesAdapter(this, ynAiteList);
        members_recycler.setAdapter(mAdapter);
        noticeMembersServiceInit();
        if (phoneNames.size() > 0) {
            for (int i = 0; i < phoneNames.size(); i++) {
                aite_sel_hor.addView(CreateTextView(phoneNames.get(i), false));
            }
            aite_hsv_tip.setVisibility(View.GONE);
            aite_hsv.setVisibility(View.VISIBLE);
        } else {
            aite_hsv.setVisibility(View.GONE);
            aite_hsv_tip.setVisibility(View.VISIBLE);
        }
        edit_text.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.length() > 0) {
                    edit_text_sure.setVisibility(View.VISIBLE);
                } else {
                    edit_text_sure.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
    }


    private void noticeMembersServiceInit() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + "GetUserYinianFriend")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAiteResponse ynAiteResponse = gson.fromJson(s, YNAiteResponse.class);
                        if (ynAiteResponse != null && ReqUtils.isSuccess(ynAiteResponse.getCode())) {
                            // 通知成员更新
                            ynAiteList.addAll(ynAiteResponse.getData());
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                sendBroadcast(new Intent("updateeditphone"));
                finish();
                break;
            case R.id.tv_phone:
                startActivity(new Intent(this, AitePhoneSelectActivity.class));
                break;
            case R.id.edit_text_sure:
                String edTx = edit_text.getText().toString();
                if (StringUtils.isEmpty(edTx)) {
                    Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                aite_sel_hor.addView(CreateTextView(edTx, true));
                edit_text.setText("");
                if (phoneNames.size() > 0) {
                    aite_hsv_tip.setVisibility(View.GONE);
                    aite_hsv.setVisibility(View.VISIBLE);
                } else {
                    aite_hsv.setVisibility(View.GONE);
                    aite_hsv_tip.setVisibility(View.VISIBLE);
                }
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
            default:
                break;
        }
    }


    private View CreateTextView(String locationtx, boolean Isadd) {
        if (Isadd) {
            phoneNames.add(locationtx);
        }
        View lView = LayoutInflater.from(this).inflate(R.layout.yn_imagelocal_edit_locationlayout, null);
        TextView ltv = (TextView) lView.findViewById(R.id.location_layout);
        ltv.setText(locationtx);
        ltv.setTag(0);
        textViews.add(ltv);
        lView.setOnClickListener(txListener);
        return lView;
    }

    View.OnClickListener txListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            TextView ltv = (TextView) v.findViewById(R.id.location_layout);
            int tag = (int) ltv.getTag();
            if (tag != 1) {
                for (int i = 0; i < textViews.size(); i++) {
                    TextView othertx = textViews.get(i);
                    othertx.setTag(0);
                    othertx.setTextColor(Color.parseColor("#ffffff"));
                    othertx.setBackgroundResource(R.drawable.location_radio_btn);
                }
                ltv.setTextColor(Color.parseColor("#000000"));
                ltv.setBackgroundResource(R.drawable.location_radio_btn_yellow);
                ltv.setTag(1);
            } else {
                for (int i = 0; i < phoneNames.size(); i++) {
                    if (ltv.getText().toString().equals(phoneNames.get(i))) {
                        phoneNames.remove(i);
                    }
                }
                for (int i = 0; i < textViews.size(); i++) {
                    if (ltv.getText().toString().equals(textViews.get(i).getText().toString())) {
                        textViews.remove(i);
                        aite_sel_hor.removeViewAt(i);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
            if (phoneNames.size() > 0) {
                aite_hsv_tip.setVisibility(View.GONE);
                aite_hsv.setVisibility(View.VISIBLE);
            } else {
                aite_hsv.setVisibility(View.GONE);
                aite_hsv_tip.setVisibility(View.VISIBLE);
            }
        }
    };


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }


}
